package com.example.pagingdemo.paging.user;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pagingdemo.databinding.ItemUserBinding;
import com.example.pagingdemo.model.User;

/**
 * @author: tuyrt7 on 2020/9/9.
 */
public class UserPageListAdapter extends PagedListAdapter<User, UserPageListAdapter.ViewHolder> {

    public UserPageListAdapter() {
        super(new DiffUtil.ItemCallback<User>() {
            @Override
            public boolean areItemsTheSame(@NonNull User oldItem, @NonNull User newItem) {
                return oldItem.id == newItem.id;
            }

            @Override
            public boolean areContentsTheSame(@NonNull User oldItem, @NonNull User newItem) {
                return oldItem.equals(newItem);
            }
        });
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemUserBinding binding = ItemUserBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        User item = getItem(position);
        holder.bindData(item);
    }

    public class ViewHolder  extends RecyclerView.ViewHolder{
        private ItemUserBinding mBinding;

        public ViewHolder(@NonNull ItemUserBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }

        public void bindData(User user) {
            mBinding.setUser(user);
        }
    }
}
